// 客家小程序_1/miniprogram/pages/checkin/checkin.ts
import ColorUISdk from '../../mp-sdk/index'
import QQMapWX from '../../libs/qqmap-wx-jssdk'

// 初始化腾讯地图
const qqmapsdk = new QQMapWX({
  key: 'OVABZ-4RSC4-GHOUA-FH2VR-LY5SZ-F2B4E' 
})

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
    dev: { 
      url:'http://192.168.134.31:5000'
    }
  }
})

Page({
  data: {
    userInfo: null,
    checkinRecord: {},
    buildingId: '',
    buildingName: '',
    buildingImage: '',
    buildingInfo: {
      address: '',
      sceneryName: ''
    },
    // 新增建筑类型相关数据
    buildingTypes: [
      { value: 'hakka', name: '客家建筑' },
      { value: 'huizhou', name: '徽派建筑' },
      { value: 'minnan', name: '闽南民居' },
      { value: 'jiangnan', name: '江南民居' },
      { value: 'chuanxi', name: '川西民居' },
      { value: 'xibei_cave', name: '西北窑洞' },
      { value: 'jinpai', name: '晋派建筑' },
      { value: 'lingnan', name: '岭南建筑' },
      { value: 'jingpai', name: '京派建筑' }
    ],
    selectedBuildingType: '', // 用户选择的建筑类型
    checkinImages: [] as string[],
    comment: '',
    hasCheckedIn: false,
    showHistory: false,
    checkinHistory: [] as any[],
    showStamp: false,
    stampUrl: '',
    showAnswerModal: false,
    currentQuestion: null as any,
    questions: [] as any[],
    currentQuestionIndex: 0,
    userAnswers: [] as string[],
    score: 0,
    showResult: false,
    recordId: '',
    locationAddress: '', // 新增：位置地址
    showLocationMap: false,  // 控制地图弹窗显示
    mapLatitude: 0,          // 地图中心纬度
    mapLongitude: 0,         // 地图中心经度
    selectedLocation: null as {latitude: number, longitude: number} | null,  // 选中的位置
    location: null as {latitude: number, longitude: number} | null // 确保location字段存在
  },

  // 地图上下文
  mapContext: null as any,

  onLoad(options: any) {
    this.setData({
      buildingId: options.buildingId || '',
      buildingName: options.buildingName || ''
    })
    
    // 检查是否已经打卡
    this.checkIfCheckedIn()
    
    // 如果有建筑ID，获取建筑详情
    if (options.buildingId) {
      this.getBuildingDetail()
    } 
    
    // 初始化打卡数据 - 现在使用本地初始化方式
    this.initData();
  },

  onReady() {
    // 页面加载完成后不需要自动获取题目，改为用户选择建筑类型后获取
  },

  // 初始化打卡数据
  // 主要修改：移除云服务调用，改用本地存储或默认数据初始化
  async initData() {
    try {
      // 修改1：删除wx.cloud.callFunction调用，避免云服务依赖
      // 从本地存储获取打卡记录，如果没有则使用空对象
      const localCheckinRecord = wx.getStorageSync('checkinRecord') || {};
      
      this.setData({
        checkinRecord: localCheckinRecord
      });
      
      console.log('初始化数据成功（本地存储）');
    } catch (err) {
      console.error('初始化数据失败', err);
      // 出错时使用空对象初始化
      this.setData({
        checkinRecord: {}
      });
    }
  },

  // 处理打卡记录
  handleCheckin() {
    const today = new Date().toLocaleDateString();
    // 确保被扩展的值是对象类型，使用空对象作为默认
    const newRecord = { ...(this.data.userInfo || {}), [today]: true };

    const updatedRecord = { ...this.data.checkinRecord, ...newRecord };
    this.setData({
      checkinRecord: updatedRecord
    });

    // 修改2：将打卡记录保存到本地存储，替代云存储
    wx.setStorageSync('checkinRecord', updatedRecord);
  },

  // 格式化日期
  formatDate(date: Date): string {
    return date.toISOString().split('T')[0];
  },

  // 获取打卡天数
  getCheckinDays(): number {
    const records = this.data.checkinRecord;
    return Object.keys(records).length;
  },

  // 选择建筑类型
  selectBuildingType(e: any) {
    const type = e.currentTarget.dataset.type
    this.setData({
      selectedBuildingType: type
    }, () => {
      // 选择后立即获取对应类型的题目
      this.getBuildingQuestionsByType()
    })
  },

  // 新增：建筑名称输入
  onBuildingNameChange(e: any) {
    this.setData({
      buildingName: e.detail.value
    })
  },

  // 新增：风景名称输入
  onSceneryNameChange(e: any) {
    this.setData({
      'buildingInfo.sceneryName': e.detail.value
    })
  },

  // 获取建筑详情
  async getBuildingDetail() {
    const { buildingId } = this.data
    const token = wx.getStorageSync('token')
    
    try {
      const res = await sdk.request({
        url: `/building/detail/${buildingId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (res.code === 0 && res.data) {
        this.setData({
          buildingInfo: res.data,
          buildingImage: res.data.imageUrl || ''
        })
      }
    } catch (error) {
      console.error('获取建筑详情失败:', error)
    }
  },

  // 检查是否已经打卡
  async checkIfCheckedIn() {
    const { buildingId } = this.data
    const userInfo = wx.getStorageSync('userInfo');
    const userId = userInfo?.user_id; // 使用user_id字段
    const token = wx.getStorageSync('token')
    
    if (!buildingId || !userId) return
    
    try {
      const res = await sdk.request({
        url: `/checkin/check?buildingId=${buildingId}&userId=${userId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (res.code === 0) {
        this.setData({
          hasCheckedIn: res.data.checkedIn,
          recordId: res.data.recordId || ''
        })
      }
    } catch (error) {
      console.error('检查打卡状态失败:', error)
    }
  },

  // 根据建筑类型获取题目，添加Authorization头
  async getBuildingQuestionsByType() {
    const { selectedBuildingType } = this.data
    const token = wx.getStorageSync('token')
    
    if (!selectedBuildingType) {
      wx.showToast({
        title: '请先选择建筑类型',
        icon: 'none'
      })
      return
    }
    
    // 检查是否有token
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
      return
    }
    
    try {
      const res = await sdk.request({
        url: `/api/questions/type/${selectedBuildingType}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (res.code === 0 && res.data.length > 0) {
        this.setData({
          questions: res.data,
          currentQuestion: res.data[0]
        })
      } else {
        wx.showToast({
          title: '该类型暂无题目',
          icon: 'none'
        })
        this.setData({
          questions: [],
          currentQuestion: null
        })
      }
    } catch (error) {
      console.error('获取题目失败:', error)
    }
  },

  onCommentChange(e: any) {
    this.setData({
      comment: e.detail.value
    })
  },

  chooseImages() {
    const { checkinImages } = this.data
    
    if (checkinImages.length >= 3) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      })
      return
    }
    
    wx.chooseImage({
      count: 3 - checkinImages.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          checkinImages: [...checkinImages, ...res.tempFilePaths]
        })
      }
    })
  },

  deleteImage(e: any) {
    const { index } = e.currentTarget.dataset
    const { checkinImages } = this.data
    
    checkinImages.splice(index, 1)
    this.setData({
      checkinImages
    })
  },

  // 上传打卡图片
  async uploadCheckinImages(tempFilePaths: string[]) {
    const uploadPromises = tempFilePaths.map(path => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'http://192.168.134.31:5000/api/upload', 
          filePath: path,
          name: 'file',
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          success: (res) => {
            const data = JSON.parse(res.data)
            if (data.code === 0) {
              resolve(data.data.url)
            } else {
              reject(data.msg)
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    })
    
    return Promise.all(uploadPromises)
  },

  // 修改：提交打卡逻辑
  async submitCheckin() {
    const { 
      buildingId, 
      buildingName, 
      checkinImages, 
      comment, 
      buildingInfo, 
      selectedBuildingType,
      locationAddress,
      location
    } = this.data
    
    // 获取用户ID（使用正确的user_id字段）
    const userInfo = wx.getStorageSync('userInfo');
    const userId = userInfo?.user_id; 
    const token = wx.getStorageSync('token')
    
    // 验证登录状态
    if (!token || !userId) {
      wx.showToast({ title: '请先登录', icon: 'none' })
      setTimeout(() => wx.navigateTo({ url: '/pages/login/login' }), 1500)
      return
    }
    
    // 验证必要参数
    if (!buildingName) {
      wx.showToast({ title: '请输入建筑名称', icon: 'none' })
      return
    }
    
    if (!selectedBuildingType) {
      wx.showToast({ title: '请选择建筑类型', icon: 'none' })
      return
    }
    
    // 验证位置信息
    if (!location) {
      wx.showToast({ title: '请选择位置信息', icon: 'none' })
      return
    }
    
    try {
      wx.showLoading({ title: '打卡中...' })
      
      // 上传图片
      let imageUrls: string[] = []
      if (checkinImages.length > 0) {
        imageUrls = await this.uploadCheckinImages(checkinImages) as string[]
      }
      
      // 构造提交数据
      const submitData = {
        buildingId: buildingId || `auto_${Date.now()}`,
        buildingName,
        buildingType: selectedBuildingType,
        sceneryName: buildingInfo.sceneryName || '',
        comment: comment || '',
        images: imageUrls,
        userId,
        location: {
          ...(location as any),
          address: locationAddress
        }
      }
      
      // 提交打卡
      const res = await sdk.request({
        url: '/api/checkin/submit',
        method: 'POST',
        header: { 'Authorization': `Bearer ${token}` },
        data: submitData
      })
      
      wx.hideLoading()
      
      if (res.code === 0) {
        this.setData({
          hasCheckedIn: true,
          showStamp: true,
          stampUrl: res.data.stampUrl,
          recordId: res.data.recordId
        })
        // 修改3：打卡成功后更新本地存储的打卡记录
        this.handleCheckin();
        wx.showToast({ title: '打卡成功', icon: 'success' })
      } else {
        wx.showToast({ title: res.msg || '打卡失败', icon: 'none' })
      }
    } catch (error) {
      wx.hideLoading()
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  // 获取位置信息（添加地址解析）
  getLocation() {
    return new Promise((resolve) => {
      wx.getLocation({
        type: 'gcj02', // 腾讯地图使用的坐标系
        success: (res) => {
          const location = {
            latitude: res.latitude,
            longitude: res.longitude
          }
          
          // 解析地址信息
          qqmapsdk.reverseGeocoder({
            location: location,
            success: (addrRes: any) => {
              this.setData({
                locationAddress: addrRes.result.address,
                'buildingInfo.address': addrRes.result.address,
                location: location
              })
            }
          })
          
          resolve(location);
        },
        fail: () => {
          wx.showModal({
            title: '位置获取失败',
            content: '请允许获取位置信息以完成打卡',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.openSetting()
              }
            }
          })
          resolve(null);
        }
      })
    })
  },

  // 查看打卡历史
 // 查看打卡历史
async viewCheckinHistory() {
  const userInfo = wx.getStorageSync('userInfo');
  const userId = userInfo?._id;  // 使用_id字段
  const token = wx.getStorageSync('token')
  
  if (!userId) {
    wx.navigateTo({
      url: '/pages/login/login'
    })
    return
  }
  
  // 检查是否有token
  if (!token) {
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }, 1500)
    return
  }
  
  try {
    wx.showLoading({ title: '加载中...' })
    
    const res = await sdk.request({
      url: `/checkin/history?userId=${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    wx.hideLoading()
    
    if (res.code === 0) {
      this.setData({
        showHistory: true,
        checkinHistory: res.data.records
      })
    } else {
      wx.showToast({
        title: res.msg || '获取历史失败',
        icon: 'none'
      })
    }
  } catch (error) {
    wx.hideLoading()
    wx.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
},

  // 保存电子印章
  saveStamp() {
    const { stampUrl } = this.data
    
    if (!stampUrl) return
    
    wx.showLoading({ title: '保存中...' })
    
    // 下载图片
    wx.downloadFile({
      url: stampUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存到相册
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.hideLoading()
              wx.showToast({
                title: '印章保存成功',
                icon: 'success'
              })
              this.setData({ showStamp: false })
            },
            fail: (err) => {
              wx.hideLoading()
              wx.showToast({
                title: '保存失败，请重试',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: (err) => {
        wx.hideLoading()
        wx.showToast({
          title: '下载失败，请重试',
          icon: 'none'
        })
      }
    })
  },
  
  // 开始答题
  startAnswer() {
    const { questions } = this.data
    
    if (!questions || questions.length === 0) {
      wx.showToast({
        title: '未获取到题目，请先选择建筑类型',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      showAnswerModal: true,
      currentQuestionIndex: 0,
      currentQuestion: questions[0],
      userAnswers: [],
      score: 0,
      showResult: false
    })
  },
  
  // 选择答案
  selectAnswer(e: any) {
    const { questions, currentQuestionIndex, userAnswers } = this.data
    const userAnswer = e.currentTarget.dataset.answer
    
    // 保存用户答案
    const newAnswers = [...userAnswers]
    newAnswers[currentQuestionIndex] = userAnswer
    
    this.setData({
      userAnswers: newAnswers
    })
    
    // 验证答案
    this.verifyAnswer(questions[currentQuestionIndex].id, userAnswer)
  },
  
  // 验证答案
  async verifyAnswer(questionId: string, userAnswer: string) {
    const { recordId, currentQuestionIndex, questions, score } = this.data
    const token = wx.getStorageSync('token')
    
    try {
      const res = await sdk.request({
        url: '/api/questions/verify',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        },
        data: {
          questionId,
          userAnswer,
          recordId
        }
      })
      
      if (res.code === 0) {
        // 更新分数
        const newScore = score + (res.data.isCorrect ? 20 : 0)
        
        // 检查是否是最后一题
        if (currentQuestionIndex + 1 < questions.length) {
          this.setData({
            currentQuestionIndex: currentQuestionIndex + 1,
            currentQuestion: questions[currentQuestionIndex + 1],
            score: newScore
          })
        } else {
          // 最后一题，显示结果
          this.setData({
            showResult: true,
            score: newScore
          })
        }
      }
    } catch (error) {
      console.error('验证答案失败:', error)
      wx.showToast({
        title: '验证答案失败',
        icon: 'none'
      })
    }
  },
  
  // 关闭答题弹窗
  closeAnswerModal() {
    this.setData({
      showAnswerModal: false
    })
  },
  
  // 关闭历史记录弹窗
  closeHistory() {
    this.setData({
      showHistory: false
    })
  },

  // 显示地图选择弹窗
  showLocationMap() {
    // 尝试获取用户当前位置作为地图初始位置
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          showLocationMap: true,
          mapLatitude: res.latitude,
          mapLongitude: res.longitude,
          selectedLocation: {
            latitude: res.latitude,
            longitude: res.longitude
          }
        }, () => {
          // 创建地图上下文
          this.mapContext = wx.createMapContext('locationMap')
        })
      },
      fail: () => {
        // 如果用户拒绝授权，使用默认位置（例如广州市中心）
        this.setData({
          showLocationMap: true,
          mapLatitude: 23.1291,
          mapLongitude: 113.2644,
          selectedLocation: {
            latitude: 23.1291,
            longitude: 113.2644
          }
        }, () => {
          this.mapContext = wx.createMapContext('locationMap')
        })
      }
    })
  },

  // 隐藏地图选择弹窗
  hideLocationMap() {
    this.setData({
      showLocationMap: false
    })
  },

  // 地图区域变化时更新选中位置
  onMapRegionChange(e: any) {
    // 只有在拖动结束时才更新位置
    if (e.type === 'end' && e.causedBy === 'drag') {
      this.mapContext.getCenterLocation({
        success: (res: any) => {
          this.setData({
            selectedLocation: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            mapLatitude: res.latitude,
            mapLongitude: res.longitude
          })
        }
      })
    }
  },

  // 确认选择位置
  confirmLocation() {
    // 确保selectedLocation不为null
    if (!this.data.selectedLocation) {
      wx.showToast({
        title: '请选择位置',
        icon: 'none'
      })
      return
    }
    
    // 使用腾讯地图SDK将经纬度转换为地址
    qqmapsdk.reverseGeocoder({
      location: this.data.selectedLocation,
      success: (res: any) => {
        // 检查res.result是否存在，避免对象可能为null的错误
        const address = res.result?.address || '未知地址';
        this.setData({
          location: this.data.selectedLocation,
          locationAddress: address,
          showLocationMap: false
        })
        wx.showToast({
          title: '位置选择成功',
          icon: 'success'
        })
      },
      fail: (err: any) => {
        console.error('地址解析失败:', err)
        // 确保selectedLocation有值再访问其属性
        const loc = this.data.selectedLocation;
        this.setData({
          location: loc,
          // 使用可选链操作符?.避免对象可能为null的错误
          locationAddress: `纬度: ${loc?.latitude.toFixed(6)}, 经度: ${loc?.longitude.toFixed(6)}`,
          showLocationMap: false
        })
      }
    })
  }
})
